<template>
  <div class="results-container">
    <h1 class="results-title">投票结果</h1>
    <router-link to="/" class="back-link">← 返回投票</router-link>
    <div class="card">
      <ResultsChart :candidates="candidates" />
      <ul class="result-list">
        <li v-for="c in candidates" :key="c.id">
          <span class="candidate-index">{{ c.id }}.</span>
          <span class="candidate-name">{{ c.name }}</span>
          <span class="vote-count">{{ c.voteCount }} 票</span>
        </li>
      </ul>
      <div v-if="candidates.length === 0" class="empty">暂无候选人</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ethers } from 'ethers';
import { getContract } from '../utils/contract';
import ResultsChart from '../components/ResultsChart.vue';

const candidates = ref([]);

async function loadCandidates() {
  const provider = new ethers.BrowserProvider(window.ethereum);
  const contract = getContract(provider);
  const count = await contract.candidatesCount();
  const arr = [];
  for (let i = 1; i <= Number(count); i++) {
    const c = await contract.getCandidate(i);
    arr.push({
      id: Number(c.id),
      name: c.name,
      voteCount: Number(c.voteCount)
    });
  }
  candidates.value = arr;
}

onMounted(loadCandidates);
</script>

<style scoped>
.results-container {
  max-width: 520px;
  margin: 0 auto;
  padding: 34px 0 16px 0;
}

.results-title {
  text-align: center;
  font-size: 2.1rem;
  font-weight: 600;
  color: #25355a;
  margin-bottom: 25px;
  letter-spacing: 0.01em;
}

/* 商务风返回链接 */
.back-link {
  display: inline-block;
  margin-bottom: 18px;
  color: #27468a;
  font-size: 15px;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: color 0.2s, border-bottom 0.2s;
}
.back-link:hover {
  color: #1d335e;
  border-bottom: 1px solid #27468a;
}

/* 卡片样式与首页统一 */
.card {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e5e9ef;
  box-shadow: 0 2px 10px rgba(50,60,90,0.08);
  padding: 26px 16px 18px 16px;
  margin-top: 8px;
}

/* 投票结果列表 */
.result-list {
  margin-top: 18px;
  padding: 0;
  list-style: none;
}

.result-list li {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f3f4fa;
  padding: 9px 0 9px 0;
  font-size: 15.6px;
  line-height: 1.15;
}

.candidate-index {
  width: 28px;
  display: inline-block;
  font-weight: 600;
  color: #27468a;
  text-align: right;
}

.candidate-name {
  font-weight: 500;
  margin-right: 18px;
  margin-left: 4px;
  color: #25355a;
}

.vote-count {
  color: #2b8658;
  margin-left: auto;
  font-weight: 600;
  font-size: 15px;
  letter-spacing: 0.02em;
}

.empty {
  color: #7480a1;
  font-size: 15px;
  text-align: center;
  margin-top: 24px;
}

/* 响应式 */
@media (max-width: 640px) {
  .results-container {
    max-width: 98vw;
    padding: 12px 2vw 10px 2vw;
  }
  .card {
    padding: 10px 2vw 10px 2vw;
  }
  .results-title {
    font-size: 1.3rem;
    margin-bottom: 13px;
  }
}
</style>
